<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSuites, deleteSuite, createSuite, getProjects, getCases, executeSuite } from '@/api/index.js'
import { Plus, Edit, Delete, View, VideoPlay } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

// 添加防抖功能
const debounce = (fn, delay) => {
  let timeoutId
  return (...args) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => fn.apply(null, args), delay)
  }
}

const router = useRouter()
const suites = ref([])
const loading = ref(false)
const createDialogVisible = ref(false)
const createLoading = ref(false)
const projects = ref([])
const availableCases = ref([])
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const searchForm = ref({
  name: '',
  status: ''
})

const suiteForm = ref({
  name: '',
  description: '',
  status: 'ACTIVE',
  project: '',
  cases: []
})

const formRules = {
  name: [
    { required: true, message: '请输入套件名称', trigger: 'blur' },
    { min: 2, max: 100, message: '套件名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入套件描述', trigger: 'blur' },
    { min: 5, max: 500, message: '套件描述长度在 5 到 500 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择套件状态', trigger: 'change' }
  ],
  project: [
    { required: true, message: '请选择所属项目', trigger: 'change' }
  ],
  cases: [
    { required: true, message: '请选择测试用例', trigger: 'change' }
  ]
}

const suiteFormRef = ref()

const fetchSuites = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
      ...searchForm.value
    }
    const res = await getSuites(params)
    if (res.status === 200) {
      suites.value = res.data.results || []
      pagination.value.total = res.data.count || 0
    }
  } catch (error) {
    ElMessage.error('获取套件列表失败')
  } finally {
    loading.value = false
  }
}

const debouncedSearch = debounce(() => {
  pagination.value.currentPage = 1
  fetchSuites()
}, 500)

const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchSuites()
}

const handleInputSearch = () => {
  debouncedSearch()
}


const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除此套件吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    const res = await deleteSuite(row.id)
    
    // 检查后端返回的 status 字段（现在是 200）
    if (res && res.status === 200) {
      ElMessage.success(res.msg || '删除成功')
      await getSuiteList()
    } else {
      ElMessage.error(`删除失败: ${res?.msg || '未知错误'}`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除套件出错:', error)
      // 如果是网络错误或其他错误
      if (error.response) {
        // 服务器响应了错误状态码
        ElMessage.error(`删除失败: ${error.response.data?.msg || error.response.statusText}`)
      } else if (error.request) {
        // 请求已发出但没有收到响应
        ElMessage.error('删除失败: 网络错误')
      } else {
        // 其他错误
        ElMessage.error(`删除失败: ${error.message}`)
      }
    }
  }
}

const handleRun = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要执行测试套件 "${row.name}" 吗？套件中包含 ${row.cases?.length || 0} 个测试用例。`,
      '执行确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      }
    )
    
    ElMessage.info('正在执行测试套件，请稍候...')
    
    // 调用执行API
    const res = await executeSuite(row.id, {
      suite_id: row.id,
      execution_time: new Date().toISOString()
    })
    
    if (res.status === 200) {
      ElMessage.success(`测试套件 "${row.name}" 执行完成`)
      await fetchSuites() // 执行后刷新状态
      // 可以在这里打开执行结果对话框或跳转到结果页面
      console.log('执行结果:', res.data)
    } else {
      ElMessage.error('执行测试套件失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('执行测试套件失败')
    }
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    return new Date(dateString).toLocaleString('zh-CN')
  } catch (error) {
    return '-'
  }
}

const getStatusTag = (status) => {
  const statusMap = {
    'ACTIVE': { type: 'success', text: '激活' },
    'INACTIVE': { type: 'info', text: '未激活' }
  }
  return statusMap[status] || { type: '', text: status }
}

const fetchProjects = async () => {
  try {
    const res = await getProjects({ page: 1, size: 1000 })
    if (res.status === 200) {
      projects.value = res.data.results || []
    }
  } catch (error) {
    ElMessage.error('获取项目列表失败')
  }
}

const fetchCases = async () => {
  try {
    const params = { page: 1, size: 1000 }
    if (suiteForm.value.project) {
      params.project = suiteForm.value.project
    }
    const res = await getCases(params)
    if (res.status === 200) {
      availableCases.value = res.data.results || []
    }
  } catch (error) {
    ElMessage.error('获取用例列表失败')
  }
}

const showCreateDialog = () => {
  createDialogVisible.value = true
  suiteForm.value = {
    name: '',
    description: '',
    status: 'ACTIVE',
    project: '',
    cases: []
  }
  fetchProjects()
  fetchCases()
}

const handleProjectChange = () => {
  suiteForm.value.cases = []
  fetchCases()
}

const handleCreateSubmit = async () => {
  if (!suiteFormRef.value) return
  
  await suiteFormRef.value.validate(async (valid) => {
    if (valid) {
      createLoading.value = true
      try {
        const res = await createSuite(suiteForm.value)
        if (res.status === 201) {
          ElMessage.success('套件创建成功')
          createDialogVisible.value = false
          fetchSuites()
        }
      } catch (error) {
        ElMessage.error('套件创建失败')
      } finally {
        createLoading.value = false
      }
    }
  })
}

const handleCreateCancel = () => {
  createDialogVisible.value = false
  suiteForm.value = {
    name: '',
    description: '',
    status: 'ACTIVE',
    project: '',
    cases: []
  }
}

onMounted(() => {
  fetchSuites()
})
</script>

<template>
  <div class="suite-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>测试套件管理</span>
          <el-button type="primary" :icon="Plus" @click="showCreateDialog">
            新建套件
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="套件名称">
            <el-input v-model="searchForm.name" placeholder="请输入套件名称" clearable @input="handleInputSearch" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable @change="handleSearch">
              <el-option label="激活" value="ACTIVE" />
              <el-option label="未激活" value="INACTIVE" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="suites" v-loading="loading" stripe>
        <el-table-column prop="name" label="套件名称" />
        <el-table-column prop="description" label="套件描述" show-overflow-tooltip />
        <el-table-column prop="case_count" label="用例数量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status).type">
              {{ getStatusTag(scope.row.status).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="执行状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.latest_execution" :type="scope.row.latest_execution.status === 'success' ? 'success' : (scope.row.latest_execution.status === 'failed' ? 'danger' : (scope.row.latest_execution.status === 'running' ? 'warning' : 'info'))">
              {{ scope.row.latest_execution.status === 'success' ? '成功' : (scope.row.latest_execution.status === 'failed' ? '失败' : (scope.row.latest_execution.status === 'running' ? '执行中' : '未执行')) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="执行结果" min-width="120">
          <template #default="scope">
            <span v-if="scope.row.latest_execution && scope.row.latest_execution.result">{{ scope.row.latest_execution.result }}</span>
            <span v-else>-</span>
            <el-link v-if="scope.row.latest_execution && scope.row.latest_execution.report_url" :href="scope.row.latest_execution.report_url" target="_blank" type="primary" style="margin-left:8px;">报告</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="project_name" label="所属项目" />
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at || scope.row.created_time) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updated_at || scope.row.updated_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="success" :icon="VideoPlay" @click="handleRun(scope.row)">
              执行
            </el-button>
            <el-button size="small" type="primary" :icon="Edit" @click="router.push(`/suite-edit/${scope.row.id}`)">
              编辑
            </el-button>
            <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchSuites"
          @current-change="fetchSuites"
        />
      </div>
    </el-card>

    <!-- 创建测试套件对话框 -->
    <el-dialog 
      v-model="createDialogVisible" 
      title="创建测试套件" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="suiteFormRef"
        :model="suiteForm"
        :rules="formRules"
        label-width="100px"
        size="default"
      >
        <el-form-item label="套件名称" prop="name">
          <el-input
            v-model="suiteForm.name"
            placeholder="请输入套件名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="套件描述" prop="description">
          <el-input
            v-model="suiteForm.description"
            type="textarea"
            placeholder="请输入套件描述"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="所属项目" prop="project">
          <el-select 
            v-model="suiteForm.project" 
            placeholder="请选择所属项目" 
            style="width: 100%"
            @change="handleProjectChange"
          >
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="套件状态" prop="status">
          <el-radio-group v-model="suiteForm.status">
            <el-radio label="ACTIVE">激活</el-radio>
            <el-radio label="INACTIVE">未激活</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="选择用例" prop="cases">
          <el-select
            v-model="suiteForm.cases"
            placeholder="请选择测试用例"
            multiple
            style="width: 100%"
            :disabled="!suiteForm.project"
          >
            <el-option
              v-for="testCase in availableCases"
              :key="testCase.id"
              :label="`${testCase.title} (${testCase.method})`"
              :value="testCase.id"
            />
          </el-select>
          <div class="help-text">
            <el-text size="small" type="info">
              {{ suiteForm.project ? '请选择要包含在此套件中的测试用例' : '请先选择项目' }}
            </el-text>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCreateCancel">取消</el-button>
          <el-button type="primary" @click="handleCreateSubmit" :loading="createLoading">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.suite-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-area {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  .pagination-area {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .help-text {
    margin-top: 5px;
  }
}
</style>